import React, { useEffect, useState } from 'react'
import { Editor } from "react-draft-wysiwyg";
import { convertToRaw, ContentState, EditorState } from 'draft-js';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';

export default function NewsEditor(props) {
	const [editorState, setEditorState] = useState(null)
	useEffect(() => {
		if(!props.content) return
		const contentBlock = htmlToDraft(props.content);
		if (contentBlock) {
			const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
			const editorState = EditorState.createWithContent(contentState);
			setEditorState(editorState)
		}
	}, [props.content])
	return (
		<>
			<Editor
				editorState={editorState}
				toolbarClassName="toolbarClassName"
				wrapperClassName="wrapperClassName"
				editorClassName="editorClassName"
				onEditorStateChange={(val) => setEditorState(val)}
				onBlur={() => {
					props.getContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
				}}
			/>
		</>
	)
}
